package com.github.defense.plugin.gray.server;

import com.alibaba.cloud.nacos.ribbon.NacosServerIntrospector;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * @Author: lettger
 * @Date: 2021/6/10 8:43 下午
 */
@Slf4j
public class NacosServerExplainer implements ServerExplainer<Server> {

    private NacosServerIntrospector introspector;

    public NacosServerExplainer(NacosServerIntrospector introspector) {
        this.introspector = introspector;
    }

    /**
     * Nacos 获取元数据
     *
     * @param server
     * @return
     */
    @Override
    public Map getMetaData(Server server) {
        return introspector.getMetadata(server);
    }

    /**
     * 获取服务名
     *
     * @param server
     * @return
     */
    @Override
    public String getServiceId(Server server) {
        String appName = server.getMetaInfo().getAppName();
        String seviceId = appName;
        if (StringUtils.contains(appName, "@@")) {
            seviceId = StringUtils.split(appName, "@@")[1];
        }
        return seviceId;
    }

    /**
     * 获取实例ID
     *
     * @param server
     * @return
     */
    @Override
    public String getInstateId(Server server) {
        return server.getMetaInfo().getInstanceId();
    }
}
